package com.teach.sys.api;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.teach.AuthUser;
import com.teach.CodeException;
import com.teach.annotation.CheckLogin;
import com.teach.sys.entity.User;
import com.teach.sys.service.UserService;

/**
 * <pre>
 * Copyright 2022 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 * 
 * @author J.L.Zhou
 * @since 2022年11月10日 13:32:33
 * @version 1.0
 */
@RestController
@RequestMapping("/sys/my")
@Validated
public class MyApi {

  @Autowired
  private UserService userService;
  /**
   * 修改登录用户自己的密码
   * 
   * @param pwd1 - 旧密码
   * @param pwd2 - 新密码
   * @param pwd3 - 新密码确认
   */
  @PutMapping("pwd")
  @CheckLogin
  public void pwd(
      @NotEmpty(message = "旧密码不能为空")
      @Pattern(regexp = "^.{2,20}$",message = "旧密码必须由2-20个字符组成") 
      String pwd1,
      @NotEmpty(message = "新密码不能为空")
      @Pattern(regexp = "^.{2,20}$",message = "新密码必须由2-20个字符组成") 
      String pwd2,
      String pwd3) {

    if (!pwd2.equals(pwd3)) {
      throw new CodeException(1, "两次输入的密码不一致");
    }
    userService.resetPwd(AuthUser.get().getUserId(), pwd2);
  }

  
  /**
   * 登录用户修改自己的个人信息
   * @param user
   */
  @PutMapping
  public void update(@RequestBody User user) {
    //设置用户为当前登录用户
    user.setUserId(AuthUser.get().getUserId());
    //将不允许修改的字段设置为null
    user.setUserLocked(null);
    user.setUserPwd(null);
    user.setRoleId(null);
    //根据主键修改
    userService.updateById(user);
  }
}
